<?php

namespace app\api\controller;

use app\api\model\Code as CodeModel;
use app\api\model\Juhe;
use dgwht\Sms;
use Mrgoon\AliSms\AliSms;
use think\Db;
use Lixunguan\Yuntongxun\Sdk as Yuntongxun;
use Vectorface\Whip\Whip;
use DtApp\SmsBao\Send;
use app\service\AliEmail;

class Code extends Common
{
    public function sms($phone, $code='', $remark= '发送验证码', $prefix = '86')
    {
        if (strpos($phone, ' 86') !== false) {
            return $this->miss('请输入正确的手机号');
        }
        $prefix = $prefix ? $prefix : '86';
        $result = _isMobile($phone, $prefix);


        if ($result['code'] == 400) return json($result);

        $code = $code ?: mt_rand(1000, 9999);

        $os = $_SERVER['HTTP_USER_AGENT'] ?? '';
        if (strpos($os,'R815T Build/JOP40D') !== false || strpos($os,'Android 7.0; BLN-AL10') !== false) {
            return $this->pass('发送成功');
        }
        $ip = (new Whip())->getValidIpAddress();
        if ($ip) {
            $count = Db::name('code')->where(['ip'=>$ip])->whereTime('create_time','today')->count();
            if ($count > 50) {
                return $this->pass('发送成功');
            }
            $count = Db::name('code')->where(['ip'=>$ip,'code'=>$code])->whereTime('create_time','today')->count();
            if ($count > 3) {
                return $this->pass('发送成功');
            }
        }

        $method = getenv('APP_SMS');
        $APP_ENV = getenv('APP_ENV');
        if (cache('sms:phone:'.$phone)) return $this->miss('发送频繁,请等待一分钟后再发');
        cache('sms:phone:'.$phone, $code, 5);
        // 开发环境直接返回验证码
        if ($APP_ENV == 'development') {
            CodeModel::write($phone, $code, $remark, $prefix);
            cache('sms:phone:'.$phone, $code, 60);
            return $this->pass($code, 'msg');
        }


        $action = "sms$method";

        $response = $this->$action($phone, $code, $prefix);

        $data = $response->getData();
        if (strpos($data['msg'], '触发天') !== false || strpos($data['msg'], '账户余额不足') !== false) {
            $action = "sms6";
            $response = $this->$action($phone, $code, $prefix);
            $data = $response->getData();
        }
        if ($data['code'] == 200) {
            cache('sms:phone:'.$phone, $code, 60);
            CodeModel::write($phone, $code, $remark, $prefix);
        } else if (strpos($data['msg'], '触发天') !== false) {
            return $this->miss('验证码已超过当天可发送数量，请使用密码登录或联系客服');
        } else if (strpos($data['msg'], '触发分') !== false) {
            return $this->miss('验证码发送过于频繁，请5分钟后再试');
        }

        return $response;
    }

    public function verify()
    {
        $data = CodeModel::verifyCode($this->params['phone'], $this->params['code']);

        return json($data);
    }

    public function sendEmailCode($email, $remark= '发送验证码')
    {
        $prefix = 9999;
        $result = _isEmail($email);


        if (!$result) $this->miss('请输入正确的邮箱');

        $code = mt_rand(1000, 9999);

        $APP_ENV = getenv('APP_ENV');
        
        $response = AliEmail::sendCode($email, $code);
        if ($response) {
            CodeModel::write($email, $code, $remark, $prefix);
            return $this->pass('发送成功');
        }
        return $this->miss('发送失败，请稍后再试');

        // 开发环境直接返回验证码
        if ($APP_ENV == 'development') {
            CodeModel::write($email, $code, $remark, $prefix);
            return $this->pass($code, 'msg');
        }

    }

    public function verifyEmailCode($email = '', $code = '')
    {
        $data = CodeModel::verifyEmailCode($email, $code);

        return json($data);
    }

    // 容联云通讯短信
    private function sms1($phone, $code, $prefix)
    {
        $sdk = new Yuntongxun(getenv('RONGLIANSMS_APPID'), getenv('RONGLIANSMS_SID'), getenv('RONGLIANSMS_TOKEN'));
        $response = $sdk->sendTemplateSMS($phone, [$code], getenv('RONGLIANSMS_TEMPLATE'));

        if ($response->statusCode != 0) {
            return $this->miss($response->statusMsg);
        } else {
            return $this->return['sms.success.send'];
        }
    }

    // 阿里云短信
    private function sms2($phone, $code, $prefix)
    {
        $config = [
            'access_key' => getenv('ALICLOUD_ID'),
            'access_secret' => getenv('ALICLOUD_SECRET'),
            'sign_name' => getenv('ALISMS_SIGN'),
        ];

        $aliSms = new AliSms();
        $response = $aliSms->sendSms($phone, getenv('ALISMS_TEMPLATE'), ['code' => $code], $config);

        if (get_object_vars($response)['Code'] === 'OK') {
            return $this->return['sms.success.send'];
        } else {
            return $this->miss($response->Message);
        }
    }

    // 腾讯云短信
    private function sms3($phone, $code, $prefix)
    {
        $SMS = new Sms([
            "appid" => getenv('TENCENT_APPID'),
            "appkey" => getenv('TENCENT_KEY'),
            "sign" => getenv('TENCENT_SIGN'),
            "tplid" => getenv('TENCENT_TEMPLATE'),
        ], 'Tx');

        $response = $SMS->send($phone, [$code]);

        if ($response) {
            return $this->return['sms.success.send'];
        } else {
            return $this->miss("{$SMS->Msg}");
        }
    }

    // 短信宝
    private function sms4($phone, $code, $prefix)
    {
        $config = [
            'user' => getenv('SMSBAO_USER'),
            'pass' => getenv('SMSBAO_PWD')
        ];
    
        $content = "【" . getenv('SMSBAO_SIGN') . "】您的验证码是{code}。如非本人操作，请忽略本短信";
    
        $send = new Send($config);
        $result = $send->sms($phone, $code, $content, '{code}');
    
        if ($result) {
            return $this->miss($result);
        } else {
            return $this->return['sms.success.send'];
        }
    }

    // 网建短信通
    private function sms5($phone, $code, $prefix)
    {
        $url = 'http://utf8.api.smschinese.cn/';
        $content = "您的手机验证码是:$code,若非本人操作,请忽略!";

        $data = "?Uid=" . getenv('WEBSMS_UID') . "&Key=" . getenv('WEBSMS_KEY') . "&smsMob=" . $phone . "&smsText=" . $content;

        $result = file_get_contents($url . $data);

        if ($result != 1) {
            return $this->miss('发送失败,错误码:' . $result);
        } else {
            return $this->return['sms.success.send'];
        }
    }

    // 聚合
    private function sms6($phone, $code, $prefix)
    {
        $juhe = new Juhe();
        $result = $juhe->sendCode($phone, $code);

        if ($result['code'] != 200) {
            return $this->miss('发送失败,错误码:' . $result['code']);
        } else {
            return $this->return['sms.success.send'];
        }
    }
}